import React, { useEffect, useState } from "react";

import { Picker } from "@tarojs/components";
import { ToDayPickerType } from "./typings";
import { fisrtYearStr, getMouth, getYear, lastYearStr } from "./utils";
const ToDayPicker: React.FC<ToDayPickerType> = (props) => {
  const { toDay, children, onChange, defalutValue } = props;
  const [year, setYear] = useState<string[]>([]);
  const [month, setMonth] = useState<string[]>(getMouth());
  const [valueIndexs, setValueIndexs] = useState<number[]>([0, 0]);
  // 生成年份
  const renderYearOptions = () => {
    const years: string[] = getYear();
    toDay && years.unshift(fisrtYearStr);
    toDay && setValueIndexs([1, 0]);
    return years;
  };
  // 判断是否非年份-至今/1990以前
  const isNotYear = (value: string): boolean => {
    return [lastYearStr, fisrtYearStr].includes(value);
  };
  useEffect(() => {
    // 初始化
    const yearList: string[] = renderYearOptions();
    setYear(yearList);
    // 回显
    if (defalutValue) {
      const list: string[] = defalutValue.split("-");
      if (list.length === 1) {
        setValueIndexs([list[0] === fisrtYearStr ? 0 : yearList.length - 1, 0]);
        setMonth([]);
        return;
      }
      const [yearValue, monthValue] = list;
      console.log("yearValue", yearValue);
      console.log("monthValue", monthValue);
      const monthList: string[] = getMouth(Number(yearValue));
      setMonth(monthList);
      const yearIndex: number = yearList.indexOf(yearValue);
      const mouthIndex: number = monthList.indexOf(monthValue);
      setValueIndexs([yearIndex, mouthIndex]);
    }
  }, []);
  return (
    <div>
      <Picker
        mode="multiSelector"
        onChange={() => {
          const currentYear: string = year[valueIndexs[0]];
          if (isNotYear(year[valueIndexs[0]])) {
            onChange?.(currentYear);
            return;
          }
          onChange?.(`${year[valueIndexs[0]]}-${month[valueIndexs[1]]}`);
        }}
        onColumnChange={({ detail: { column, value } }) => {
          // 年份处理
          if (column === 0) {
            // 查找当前的月份值
            const curMouth = month[valueIndexs[1]];
            const newMouth: string[] = getMouth(Number(year[value]));
            setMonth(isNotYear(year[value]) ? [] : newMouth);
            // 重新赋值月份下标
            const index = newMouth.indexOf(curMouth);
            setValueIndexs([value, index === -1 ? 0 : index]);
            return;
          }
          // 月份处理
          setValueIndexs([valueIndexs[0], value]);
        }}
        value={valueIndexs}
        range={[year, month]}
      >
        {children}
      </Picker>
    </div>
  );
};

export default ToDayPicker;
